package name.sraynal.coodiary.storage;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MapStorageManager implements IStorageManager {

	List<Quote> quotes;
	
	public void createTables() {
		this.quotes = new ArrayList<Quote>();
	}

	public void store(String value, String type, Date date) {
		Quote quote = new Quote(date, value, type);
		store(quote);
	}

	public void store(Quote quote) {
		this.quotes.add(determinePosition(quote), quote);
		
//		for (int i = 0;i < this.quotes.size();i++) {
//			System.out.println(this.quotes.get(i).getDate() + " : " + this.quotes.get(i).getValue());
//		}
//		System.out.println();
	}
	
	private int determinePosition(Quote quote) {
		Date date = quote.getDate();
		
		if (this.quotes.size() == 0) {
			return 0;
		}
		
		int ceiling = this.quotes.size() - 1;
		int floor = 0;
		int median = 1000;
		
		if ((date.after(dateOf(ceiling)))
				|| (date.equals(dateOf(ceiling)))) {
			return ceiling + 1;
		} else if ((date.before(dateOf(floor)))
					|| (date.equals(dateOf(ceiling)))) {
			return floor;
		}
		
		while (Math.abs(floor - median) > 0) {
			median = floor + (ceiling - floor)/2;

			if (date.after(dateOf(median))) {
				floor = median;
			} else if (date.before(dateOf(median))) {
				ceiling = median;
			} else {
				floor = median;
			}
		}
		
		if ((date.before(dateOf(median)))) {
			return median - 1;
		}
		
		return median;
	}
	
	private Date dateOf(int index) {
		return this.quotes.get(index).getDate();
	}

	public List<Quote> getQuotes() {
		return this.quotes;
	}
}
